//
//  ViewController.m
//  CheckIn
//
//  Created by ren on 10/01/2018.
//  Copyright © 2018 bryan. All rights reserved.
//

#import "ViewController.h"
#import "CommonDefine.h"
#import "CheckInDataManage.h"
#import "StringAndDateHandle.h"
#import "ShowDataViewController.h"
#import "FileManage.h"

typedef void(^OKAction)(BOOL ok);

@interface ViewController ()

@property (nonatomic, strong) NSUserDefaults *userDefaults;
@property (nonatomic, strong) StringAndDateHandle *handle;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _userDefaults = [NSUserDefaults standardUserDefaults];
    [[CheckInDataManage sharedInstance] removeCheckInAndOutInfo];
    _handle = [StringAndDateHandle sharedInstance];
}

- (IBAction)buttonClickAction:(UIButton *)sender {
    switch (sender.tag) {
        case 10:
            [self workCheckIn];
            break;
        case 11:
            [self workCheckOut];
            break;
        case 12:{
                NSURL *fileUrl = [self fileToURL:[FileManage currentMonthFile]];
                [self shareWithActivityItems:@[fileUrl]];
            }
            break;
        case 13:
            
            break;
        case 14:
            [self presentDatRecordPage];
            break;
        default:
            break;
    }
}
//签到
- (void)workCheckIn
{
    NSString *checkIn = [_userDefaults valueForKey:kWorkCheckIn];
    if (checkIn && ![checkIn isEqualToString:@""]) {
        [self showAlert:@"已有上班签到数据，是否要重新签到？" record:YES complicated:^(BOOL ok) {
            if (ok) {
                [self setValueForUserDefaults:[self.handle nowToString] key:kWorkCheckIn];
            }
        }];
    }
    else {
        [self setValueForUserDefaults:[self.handle nowToString] key:kWorkCheckIn];
    }
}
//签退
- (void)workCheckOut
{
    [self setValueForUserDefaults:[self.handle nowToString] key:kWorkCheckOut];
    [self calcWorkTime];
}
//跳转到数据记录
- (void)presentDatRecordPage
{
    ShowDataViewController *showDataVC = [ShowDataViewController new];
    [self presentViewController:showDataVC animated:YES completion:nil];
}

#pragma mark - handle data

- (void)setValueForUserDefaults:(NSString *)now key:(NSString *)key
{
    if (_userDefaults && now && ![now isEqualToString:@""] && key && ![key isEqualToString:@""])
    {
        [_userDefaults setValue:now forKey:key];
        [_userDefaults synchronize];
    }
}

- (void)calcWorkTime
{
    NSString *checkIn = [_userDefaults valueForKey:kWorkCheckIn];
    NSString *checkOut = [_userDefaults valueForKey:kWorkCheckOut];
    if (!checkIn || [checkIn isEqualToString:@""]) {
        if (checkOut && ![checkOut isEqualToString:@""]) {
            [self noCheckIn:checkOut];
        }
        else {
            [self showAlert:@"没有下班签退数据" record:NO complicated:nil];
        }
    }
    else {
        if (checkOut && ![checkOut isEqualToString:@""]) {
            [self haveCheckIn:checkIn checkOut:checkOut];
        }
    }
}
//无签到数据，签退时处理
- (void)noCheckIn:(NSString *)checkOut
{
    NSDate *checkOutDate = [self.handle stringToDate:checkOut formatter:kDateYMDHMS];
    NSString *checkOutStirng = [self.handle dateToString:checkOutDate formatter:KDateHour];
    NSLog(@"%@", checkOutStirng);
    if ([checkOutStirng integerValue] > 20) {
        [self showAlert:@"没有上班签到数据，下班签退时间在晚上8点之后，是否计入加班数据？" record:YES complicated:^(BOOL ok) {
            if (ok) {
                NSString *checkOut = [_userDefaults valueForKey:kWorkCheckOut];
                [self recordOvertimeData:checkOut];
            }
        }];
    }
    else {
        [self showAlert:@"还没到加班签退时间，请继续加油！！！" record:NO complicated:nil];
    }
}
//签到和签退数据都有
- (void)haveCheckIn:(NSString *)checkIn checkOut:(NSString *)checkOut
{
    NSDate *checkInDate = [self.handle stringToDate:checkIn formatter:kDateYMDHMS];
    NSDate *checkOutDate = [self.handle stringToDate:checkOut formatter:kDateYMDHMS];
    NSString *checkOutStirng = [self.handle dateToString:checkOutDate formatter:KDateHour];
    if ([checkOutStirng integerValue] >= 20) {
        NSTimeInterval dateDis = [checkOutDate timeIntervalSinceDate:checkInDate];
        if ((dateDis / 3600.0) < 9) {
            [self showAlert:@"上班时间不足8小时，是否计入加班数据？" record:YES complicated:^(BOOL ok) {
                if (ok) {
                    NSString *checkOut = [_userDefaults valueForKey:kWorkCheckOut];
                    [self recordOvertimeData:checkOut];
                }
            }];
        }
        else {
            NSString *checkOut = [_userDefaults valueForKey:kWorkCheckOut];
            [self recordOvertimeData:checkOut];
        }
    }
    else {
        [self showAlert:@"还没到加班签退时间，请继续加油！！！" record:NO complicated:nil];
    }
}

#pragma mark - alert

- (void)showAlert:(NSString *)msg record:(BOOL)record complicated:(OKAction)complicated
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)0.2*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                                                                  if (complicated) {
                                                                      complicated(YES);
                                                                  }
                                                              });
                                                          }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              if (complicated) {
                                                                  complicated(NO);
                                                              }
                                                          }];
    [alertController addAction:okAction];
    if (record) {
        [alertController addAction:cancelAction];
    }
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - record

- (void)recordOvertimeData:(NSString *)dateString
{
    BOOL isCreate = [FileManage createFileDirectory];
    if (isCreate) {
        NSString *currentMonthPath = [FileManage currentMonthFile];
        NSURL *url = [NSURL fileURLWithPath:currentMonthPath];
        NSArray *contentList = [FileManage fileContent:url];
        NSMutableIndexSet *indexSet = [self deleteIndexSet:contentList dateString:dateString];
        NSString *contentString = [self generateContent:contentList indexSet:indexSet dateString:dateString];
        if (contentString && ![contentString isEqualToString:@""]) {
            [self writeToFile:dateString path:currentMonthPath];
        }
        else {
            NSLog(@"data is empty");
        }
    }
    else {
        NSLog(@"Create Directory Failed");
    }
}

- (NSMutableIndexSet *)deleteIndexSet:(NSArray *)contentList dateString:(NSString *)dateString
{
    NSInteger index = 0;
    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
    for (NSString *content in contentList) {
        NSString *dateYMD = [dateString substringToIndex:10];
        if (content && ![content isEqualToString:@""] && content.length > 10) {
            NSString *contentYMD = [content substringToIndex:10];
            if ([dateYMD compare:contentYMD options:NSCaseInsensitiveSearch] == NSOrderedSame) {
                [indexSet addIndex:index];
            }
        }
        index ++;
    }
    return indexSet;
}

- (NSString *)generateContent:(NSArray *)contentList indexSet:(NSMutableIndexSet *)indexSet dateString:(NSString *)dateString
{
    NSMutableArray *arrayList = [NSMutableArray array];
    if (contentList && [contentList count] && indexSet) {
        arrayList = [contentList mutableCopy];
        [arrayList removeObjectsAtIndexes:indexSet];
    }
    [arrayList addObject:dateString];
    NSString *contentString = [arrayList componentsJoinedByString:@"\r\n"];
    return contentString;
}

//内容写入
- (void)writeToFile:(NSString *)dateString path:(NSString *)currentMonthPath
{
    BOOL res = [dateString writeToFile:currentMonthPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (res) {
        NSLog(@"写成功");
    }
    else {
        NSLog(@"写失败");
    }
}
//文件中追加内容
- (void)fileIncreaseNewContent:(NSString *)dateString path:(NSString *)currentMonthPath
{
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:currentMonthPath];
    [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
    NSData* stringData  = [dateString dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:stringData]; //追加写入数据
    [fileHandle closeFile];
}

#pragma mark - share

- (void)shareWithActivityItems:(NSArray *)activityItems
{
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    NSArray *excludedActivities = @[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
                                    UIActivityTypePostToWeibo,
                                    UIActivityTypeMessage,
                                    UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
                                    UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
                                    UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
                                    UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
    activityVC.excludedActivityTypes = excludedActivities;
    [self presentViewController:activityVC animated:YES completion:nil];
}

- (NSURL *)fileToURL:(NSString*)filename
{
    NSString *filePath = [[FileManage document] stringByAppendingPathComponent:filename];
    return [NSURL fileURLWithPath:filePath];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
